package com.bitcola.security.activity.controller;

import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.bitcola.security.activity.biz.ApplyBiz;
import com.bitcola.entity.ApplyLog;
import com.bitcola.security.activity.mapper.ColaUserBalanceMapper;
import com.bitcola.security.activity.mapper.LabsApplyLogMapper;
import com.bitcola.security.auth.client.annotation.IgnoreUserToken;
import com.bitcola.security.auth.common.util.EncoderUtil;
import com.bitcola.security.common.constant.ResponseCode;
import com.bitcola.security.common.context.BaseContextHandler;
import com.bitcola.security.common.exception.NoAmountException;
import com.bitcola.security.common.exception.ParamLimitException;
import com.bitcola.security.common.msg.AppResponse;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("labsApply")
public class LabsApplyController {
    @Autowired
    ApplyBiz applyBiz;
    @Autowired
    ColaUserBalanceMapper balanceMapper;


    @Autowired
    LabsApplyLogMapper labsApplyLogMapper;



    @RequestMapping(value = "query")
    @IgnoreUserToken
    public AppResponse query(String status){
        return AppResponse.ok().data(applyBiz.queryProject(status));
    }




    @RequestMapping(value = "apply")
    public AppResponse apply(@RequestBody Map<String,String> param){



        String userId= BaseContextHandler.getUserID();


        BigDecimal number=new BigDecimal(param.get("number"));
        BigDecimal dudect=new BigDecimal(param.get("dudect"));

        String pin=param.get("pin");
        String labsProjectId=param.get("labsProjectId");

        var project=applyBiz.getById(labsProjectId);
        long now=System.currentTimeMillis();
        long start=project.getStartTime().getTime();
        long end=project.getEndTime().getTime();

        if(!(now>=start&&now<=end))             return AppResponse.error(ResponseCode.TIME_NOT_RANGE, ResponseCode.TIME_NOT_RANGE_MESSAGE);

        if(project.getRemindNumber().compareTo(number)<0) throw new NoAmountException("");
        if(number.compareTo(project.getBuyMaxAmount())>0||number.compareTo(project.getBuyMinAmount())<0) throw new ParamLimitException("");
        if(!EncoderUtil.matches(pin,balanceMapper.getMoneyPassword(userId))){
            return AppResponse.error(ResponseCode.PIN_ERROR_CODE, ResponseCode.PIN_ERROR_MESSAGE);
        }

        ApplyLog log= applyBiz.apply(userId,number,dudect,labsProjectId);

        return AppResponse.ok().data(log);


    }

    @RequestMapping(value = "labsApply")
    public AppResponse labsApply(String status){



      return query(status);


    }



    @RequestMapping(value = "queryLogs")
    public AppResponse queryLogs(Long end,int size,String labsProjectId,Integer rush){
        Example example=new Example(ApplyLog.class);
        Example.Criteria criteria= example.createCriteria();
        criteria.andEqualTo("userId",BaseContextHandler.getUserID());
        if (end==null||end==0)          end=System.currentTimeMillis();
        criteria.andLessThanOrEqualTo("createTime",new Date(end));
        if(rush!=null) criteria.andEqualTo("rush",rush);
        if(labsProjectId!=null) criteria.andEqualTo("projectId",labsProjectId);


        example.orderBy("createTime").desc();


       var list= labsApplyLogMapper.selectByExampleAndRowBounds(example,new RowBounds(0,size));


        List<Map<String,Object>>result=new ArrayList<>(list.size());
       list.forEach(log->{
           Map<String,Object>map=new HashMap<>(4);
           map.put("log",log);
           map.put("project",applyBiz.getById(log.getProjectId()));
           result.add(map);

       });


        return AppResponse.ok().data(result);
    }











}
